<template>
  <div class="set-manager-container">
    <!-- 顶部导航区域 -->
    <div class="header-wrapper">
      <!-- 顶部导航 -->
      <div class="header">
        <van-icon name="arrow-left" class="back-icon" @click="goBack" />
        <div class="header-title">设置部门主管</div>
        <div class="cancel-btn" @click="goBack">取消</div>
      </div>

      <!-- 搜索框 -->
      <div class="search-container">
        <van-search
          autocomplete="off"
          v-model="searchValue"
          placeholder="搜索"
          shape="round"
          background="transparent"
          left-icon="search"
          @search="onSearch"
          @focus="onSearchFocus"
        />
      </div>
    </div>

    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <span class="breadcrumb-item clickable" @click="goToRoot">{{ rootDepartment.name }}</span>
      <van-icon name="arrow" class="breadcrumb-arrow" />
      <span class="breadcrumb-item current">{{ currentDepartment.name }}</span>
    </div>

    <!-- 加载状态 - 骨架屏 -->
    <div v-if="loading" class="skeleton-container">
      <van-skeleton :row="6" :loading="true" avatar />
    </div>

    <!-- 人员列表 -->
    <div class="member-list" v-else-if="filteredMembers && filteredMembers.length > 0">
      <!-- 部门成员 -->
      <div 
        v-for="member in filteredMembers"
        :key="member.id"
        class="member-item"
        @click="selectMember(member)"
      >
       <!-- 选择状态 -->
        <div class="select-status">
          <van-icon 
            :name="selectedMember?.id === member.id ? 'checked' : 'circle'" 
            :class="selectedMember?.id === member.id ? 'selected' : 'unselected'"
          />
        </div>
        <div class="member-avatar">
              <AvatarDisplay :url="member.url" :name="member.name" />
            </div>
        <div class="member-info">
          <div class="member-name">
            {{ member.name }}
          </div>
          <div class="member-position">{{ member.position }}</div>
        </div>
       
      </div>
    </div>

    <!-- 空状态 -->
    <div v-else class="empty-state">
      <div class="empty-icon">
        <img src="/src/assets/homeOther/user_icon.png" alt="">
      </div>
      <div class="empty-text">暂无成员</div>
    </div>

    <!-- 底部确认按钮 -->
    <div class="bottom-actions">
      <div class="bottom-content">
        <div class="selected-info" v-if="selectedMember">
          已选择：<span class="select-number">{{ selectedMember.name }}</span>
        </div>
        <div class="selected-info" v-else>
             暂未选择员工
        </div>
        <div 
          class="confirm-btn" 
          :class="{ disabled: !selectedMember }"
          @click="confirmSelection"
        >
          <span>确定</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast } from 'vant'
import { findDepartmentById, setDepartmentLeader, getNoDepartmentMembers, type DepartmentMember, type SetLeaderResponse, type NoDepartmentMember } from '@/api/organization'
import { getUserPicture } from '@/api/contract'
import { smartGoBack } from '@/utils/navigation'
import defaultAvatar from '@/assets/homeOther/picture.png'
import AvatarDisplay from '@/components/UserAvatar/AvatarDisplay.vue'

// 路由实例
const router = useRouter()
const route = useRoute()

// 搜索值
const searchValue = ref('')

// 选中的成员
const selectedMember = ref<Member | null>(null)

// 加载状态 - 初始为false，避免闪烁
const loading = ref(false) // 初始为true，显示加载状态

// 成员数据类型（适配前端显示需求）
interface Member {
  id: number
  name: string
  position: string
  avatar: string
  url: string // 添加url字段用于头像组件
  isManager: boolean
}

// 成员列表
const members = ref<Member[]>([])

// 部门数据类型
interface Department {
  id: string
  name: string
  description: string
  memberCount: number
  parentId?: string
}

// 根部门
const rootDepartment = reactive({
  id: 'root',
  name: '北京君初律师事务所'
})

// 当前部门 - 根据路由参数获取
const currentDepartment = reactive({
  id: '',
  name: ''
})

// 部门映射
const departmentMap: Record<string, Department> = {
  'hr': {
    id: 'hr',
    name: '人力资源部',
    description: '负责人力资源管理',
    memberCount: 4
  },
  'finance': {
    id: 'finance',
    name: '总经办',
    description: '负责总经办事务',
    memberCount: 3
  },
  'rd': {
    id: 'rd',
    name: '研发部',
    description: '负责技术研发',
    memberCount: 5
  },
  'tech': {
    id: 'tech',
    name: '技术部',
    description: '负责技术支持',
    memberCount: 3
  },
  'art': {
    id: 'art',
    name: '美术部',
    description: '负责美术设计',
    memberCount: 2
  },
  'sales': {
    id: 'sales',
    name: '销售部',
    description: '负责销售业务',
    memberCount: 4
  }
}

// 过滤后的成员列表（根据搜索条件）
const filteredMembers = computed(() => {
  if (!searchValue.value) {
    return members.value
  }
  return members.value.filter(member => 
    member.name.toLowerCase().includes(searchValue.value.toLowerCase()) ||
    member.position.toLowerCase().includes(searchValue.value.toLowerCase())
  )
})

// 获取用户头像
const getUserAvatar = async (url: string): Promise<string> => {
  if (!url || url.trim() === '') {
    return defaultAvatar
  }
  
  try {
    const avatarBlob = await getUserPicture(url)
    return URL.createObjectURL(avatarBlob)
  } catch (error) {
    console.error('获取用户头像失败:', error)
    return defaultAvatar
  }
}

// 获取部门成员列表
const fetchMembers = async (departmentId: string) => {
  try {
    loading.value = true
    const response = await findDepartmentById(departmentId)
    
    if (response.code === 0) {
      // 处理成员数据，获取头像
      const membersWithAvatars = await Promise.all(
        response.data.map(async (member: DepartmentMember) => {
          const avatar = await getUserAvatar(member.url)
          return {
            id: member.id,
            name: member.name,
            position: member.isLeader ? '主管' : '成员',
            avatar: avatar,
            url: member.url, // 保留原始url用于头像组件
            isManager: member.isLeader
          }
        })
      )
      
      members.value = membersWithAvatars
      console.log('部门成员数据加载成功:', response.data)
    } else {
      showToast(response.msg || '获取成员列表失败')
    }
  } catch (error) {
    console.error('获取成员列表失败:', error)
    showToast('获取成员列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 返回上一页
const goBack = () => {
  smartGoBack(router)
}

// 返回根部门（组织架构首页）
const goToRoot = () => {
  router.push('/organization')
}

// 搜索功能
const onSearch = (value: string) => {
  // 跳转到搜索页面，传递搜索关键词
  router.push({
    path: '/organization/search',
    query: {
      keyword: value
    }
  })
}

// 搜索框获取焦点事件
const onSearchFocus = () => {
  // 跳转到搜索页面
  router.push('/organization/search')
}

// 选择成员
const selectMember = (member: Member) => {
  if (selectedMember.value?.id === member.id) {
    selectedMember.value = null // 取消选择
  } else {
    selectedMember.value = member // 选择新成员
  }
}

// 确认选择
const confirmSelection = async () => {
  if (!selectedMember.value) {
    showToast('请选择一位成员作为主管')
    return
  }

  const fromPage = route.query.from as string
  
  // 如果是从添加子部门页面跳转过来的，直接返回并传递选中的主管信息
  if (fromPage === 'add-department') {
    showToast(`已选择 ${selectedMember.value.name} 为部门主管`)
    
    const queryParams = {
      selectedManagerId: selectedMember.value.id,
      selectedManagerName: selectedMember.value.name,
      selectedManagerPosition: selectedMember.value.position,
      parentId: route.query.parentId,
      from: route.query.originalFrom || route.query.from || 'index',
      mode: route.query.mode
    }
    
    console.log('🚀 返回add-department页面，传递参数:', queryParams)
    
    // 返回到添加子部门页面，并传递选中的主管信息
    router.push({
      path: '/organization/add-department',
      query: queryParams
    })
    return
  }

  if (!currentDepartment.id) {
    showToast('部门ID不存在')
    return
  }
  
  try {
    loading.value = true
    const response: SetLeaderResponse = await setDepartmentLeader(
      currentDepartment.id,
      selectedMember.value.id
    )
    
    if (response.code === 0) {
      showToast(`已设置 ${selectedMember.value.name} 为部门主管`)
      
      // 返回上一页
      setTimeout(() => {
        router.back()
      }, 1500)
    } else {
      showToast(response.msg || '设置主管失败')
    }
  } catch (error) {
    console.error('设置主管失败:', error)
    showToast('设置主管失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 获取无部门成员列表
const fetchNoDepartmentMembers = async () => {
  try {
    loading.value = true
    const response = await getNoDepartmentMembers()
    if (response.code === 0) {
      // 将NoDepartmentMember转换为DepartmentMember格式，并获取头像
      const membersWithAvatars = await Promise.all(
        response.data.map(async (member: NoDepartmentMember) => {
          const avatar = await getUserAvatar(member.url)
          return {
            id: member.id,
            name: member.name,
            phone: member.phone,
            position: member.position,
            avatar: avatar,
            url: member.url, // 保留原始url用于头像组件
            isManager: false
          }
        })
      )
      
      members.value = membersWithAvatars
      console.log('无部门成员数据加载成功:', response.data)
    } else {
      showToast(response.msg || '获取成员列表失败')
    }
  } catch (error) {
    console.error('获取无部门成员失败:', error)
    showToast('获取成员列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 初始化部门信息
const initDepartment = () => {
  const fromPage = route.query.from as string
  const departmentId = route.query.departmentId as string
  
  // 如果是从添加子部门页面跳转过来的
  if (fromPage === 'add-department') {
    currentDepartment.id = 'new-department'
    currentDepartment.name = '选择部门主管'
    fetchNoDepartmentMembers()
    return
  }
  
  console.log('设置主管页面 - 接收到的部门ID:', departmentId)
  
  if (!departmentId) {
    showToast('部门ID参数缺失')
    router.replace('/organization')
    return
  }
  
  // 检查是否是预定义的部门ID
  const department = departmentMap[departmentId]
  
  if (department) {
    // 使用预定义的部门信息
    currentDepartment.id = department.id
    currentDepartment.name = department.name
    fetchMembers(departmentId)
  } else {
    // 处理动态部门ID（数字ID）
    currentDepartment.id = departmentId
    currentDepartment.name = `部门${departmentId}`
    fetchMembers(departmentId)
  }
}

// 页面加载
onMounted(() => {
  // 优化加载体验：延迟显示loading，避免闪烁
  let loadingTimer: NodeJS.Timeout | null = null
  
  // 延迟显示loading，避免闪烁
  loadingTimer = setTimeout(() => {
    loading.value = true
  }, 200)
  
  // 立即开始数据加载
  requestAnimationFrame(() => {
    initDepartment()
    // 数据加载完成后清除定时器
    setTimeout(() => {
      if (loadingTimer) {
        clearTimeout(loadingTimer)
        loadingTimer = null
      }
    }, 100)
  })
  
  console.log('设置部门主管页面已加载')
})
</script>

<style lang="scss" scoped>
@import url('./style/set-manager.scss');


</style>